<template>
  <div class="features-module">
    <div class="module-header">
      <h3 class="module-title">更多功能</h3>
    </div>

    <div class="features-grid">
      <div class="feature-item" @click="navigateTo('/address')">
        <div class="icon-wrapper">
          <i class="fa fa-map-marker"></i>
        </div>
        <div class="label">我的地址</div>
      </div>

      <div class="feature-item">
        <div class="icon-wrapper">
          <i class="fa fa-headphones"></i>
        </div>
        <div class="label">我的客服</div>
      </div>

      <div class="feature-item">
        <div class="icon-wrapper">
          <i class="fa fa-comment"></i>
        </div>
        <div class="label">小饿评审</div>
      </div>

      <div class="feature-item">
        <div class="icon-wrapper">
          <i class="fa fa-gift"></i>
        </div>
        <div class="label">下单返</div>
      </div>
      
      <!-- 新增商家入口按钮 -->
      <div class="feature-item" @click="handleBusinessClick">
        <div class="icon-wrapper business-icon">
          <i class="fa fa-shopping-bag"></i>
        </div>
        <div class="label">商家版</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { computed } from 'vue';
import { useUserStore } from '../../store/pinia_store_user';
import axios from 'axios';

const router = useRouter();
const userStore = useUserStore();

const navigateTo = (path) => {
  router.push(path);
};

// 处理商家入口点击事件
const handleBusinessClick = async () => {
  // 检查是否已登录
  if (!userStore.isLoggedIn) {
    alert('请先登录');
    router.push('/login');
    return;
  }

  try {
    // 确保用户信息已加载
    if (!userStore.userInfo || Object.keys(userStore.userInfo).length === 0) {
      await userStore.fetchUserInfo();
    }
    
    const userInfo = userStore.userInfo;
    const authorities = userInfo.authorities || [];
    
    // 检查用户权限
    const hasBusinessRole = authorities.some(auth => auth.name === 'BUSINESS' || auth.name === 'ROLE_BUSINESS');
    const hasAdminRole = authorities.some(auth => auth.name === 'ADMIN' || auth.name === 'ROLE_ADMIN');
    
    if (hasBusinessRole) {
      // 具有BUSINESS权限
      // 获取当前用户关联的商家列表
      const response = await axios.get(`/api/businesses/user/${userInfo.id}`);
      let userBusinesses = [];
      
      if (response && response.data && response.data.success && Array.isArray(response.data.data)) {
        userBusinesses = response.data.data;
      } else if (response && Array.isArray(response.data)) {
        userBusinesses = response.data;
      }
      
      // 保存商家列表
      localStorage.setItem("business_stores", JSON.stringify(userBusinesses));
      
      if (userBusinesses.length === 0) {
        // 有BUSINESS权限但没有店铺，直接跳转到商家注册页面的第二步
        console.log("用户有BUSINESS权限但未关联任何店铺，直接跳转到商家注册第二步");
        localStorage.setItem('skip_to_step_two', 'true'); // 设置标记，指示商家注册页面直接跳到第二步
        router.push('/businessRegister');
      } else if (userBusinesses.length === 1) {
        // 只有一个商家，直接选择
        localStorage.setItem("business", JSON.stringify(userBusinesses[0]));
        router.push('/businessManage');
      } else {
        // 有多个商家，跳转到店铺选择页面
        router.push('/businessStoreSelector');
      }
    } else if (hasAdminRole) {
      // 具有ADMIN权限，获取所有店铺
      const response = await axios.get('/api/businesses');
      let allBusinesses = [];
      
      if (response && response.data && response.data.success && Array.isArray(response.data.data)) {
        allBusinesses = response.data.data;
      } else if (response && Array.isArray(response.data)) {
        allBusinesses = response.data;
      }
      
      // 保存所有商家列表
      localStorage.setItem("business_stores", JSON.stringify(allBusinesses));
      
      // 跳转到店铺选择页面
      router.push('/businessStoreSelector');
    } else {
      // 无商家权限，跳转到商家注册页面的第一步（身份验证）
      console.log("用户无商家权限，跳转到商家注册第一步进行身份验证");
      // 确保不设置skip_to_step_two标记
      localStorage.removeItem('skip_to_step_two');
      router.push('/businessRegister');
    }
  } catch (error) {
    console.error('获取商家信息失败:', error);
    alert('获取商家信息失败，请重试');
  }
};
</script>

<style scoped>
.features-module {
  background-color: white;
  margin: 15px;
  border-radius: 8px;
  padding: 15px;
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.module-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 5px;
}

.icon-wrapper i {
  font-size: 20px;
  color: #333;
}

.label {
  font-size: 12px;
  color: #666;
}

/* 商家入口按钮特殊样式 */
.business-icon {
  background-color: #ebf7ff;
  border: 1px solid #c7e6ff;
  box-shadow: 0 2px 5px rgba(0, 151, 255, 0.1);
  transition: all 0.3s ease;
}

.business-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 151, 255, 0.2);
}

.business-icon i {
  color: #0097ff;
  font-size: 22px;
}
</style> 